//app.js
import {
  onLogin,
  checkIsBind,
  bindPartner,
  promoteSendIntegral,
  getVIPInfor
} from 'api/apis.js'
App({
  onLaunch: function(option) {
    console.log(this.globalData)
    this.globalData.redirect = option.query.redirect || '/pages/index/index'
    this.globalData.appHot = 1
    this._login()
    this._update()
    this.globalData.option = option
  },
  onShow(option) {
    if (option.path.lastIndexOf('fakeIndex') !== -1) {
      if (this.globalData.appHot !== 1) {
        this.globalData.redirect = option.query.redirect || '/pages/index/index'
        this._login()
        this.globalData.option = option
      }
    }
  },
  onHide() {
    this.globalData.appHot = 0
  },
  _login() {
    //登录
    this.globalData.getOpenid = () => {
      wx.showLoading({
        title: '登录中...',
        mask: true
      })
      let p = new Promise((resolve, reject) => {
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            onLogin({
              data: {
                code: res.code
              },
              success: res => {
                if (res.state) {
                  this.globalData.openid = JSON.parse(res.message).openid
                  resolve()
                }
              }
            })
          }
        })
      })
      return p
    }
    this.globalData.getInfo = () => {
      let p = new Promise((resolve, reject) => {
        //获取用户信息
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                lang: 'zh_CN',
                success: res => {
                  // 可以将 res 发送给后台解码出 unionId
                  this.globalData.userInfo = res.userInfo
                  resolve(true)
                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  // if (this.userInfoReadyCallback) {
                  //   this.userInfoReadyCallback(res)
                  // }
                }
              })
            } else {
              reject(false)
            }
          }
        })
      })
      return p
    }
    this.globalData.getIsVip = () => {
      let p = new Promise((resolve, reject) => {
        getVIPInfor({
          data: {
            openid: this.globalData.openid
          },
          success: res => {
            if (res.state) {
              this.globalData.vipInfo = res.data
              resolve()
            } else {
              reject()
            }
          }
        })
      })

    }
    this.globalData.checkIsBind = () => {
      let p = new Promise((resolve, reject) => {
        checkIsBind({
          data: {
            role: 'UserCRM',
            openid: this.globalData.openid,
            nickname: this.globalData.userInfo.nickName,
            headimgurl: this.globalData.userInfo.avatarUrl,
            addr: this.globalData.userInfo.province + this.globalData.userInfo.city,
          },
          success: res => {
            if (res.state) {
              resolve(res)
            } else {
              reject(res)
            }
          }
        })
      })
      return p
    }
    this.globalData.getOpenid()
      .then(() => {
        return this.globalData.getInfo()
      })
      .then((res) => {
        return this.globalData.getIsVip()
      }, (res) => {
        wx.reLaunch({
          url: '../authorization/authorization',
        })
        return this.globalData.getIsVip()
      })
      .then((res) => {
        if (this.globalData.userInfo) {
          this._bind()
          wx.hideLoading()
          wx.reLaunch({
            url: this.globalData.redirect,
          })
        }
      }, (res) => {
        // wx.hideLoading()
        if (this.globalData.userInfo) {
          this._bind()
          wx.hideLoading()
          wx.reLaunch({
            url: this.globalData.redirect,
          })
        }
      })
      
  },
  _bind() {
    if (this.globalData.option.query.scene === undefined) {
      this.globalData.checkIsBind()
      return false
    }
    let fromOpenid = decodeURIComponent(this.globalData.option.query.scene).split(',')[0]
    let from = decodeURIComponent(this.globalData.option.query.scene).split(',')[1]
    if (from === 'cu') {
      promoteSendIntegral({
        data: {
          fromopenid: fromOpenid,
          toopenid: this.globalData.openid
        },
        success: res => {
          this.globalData.checkIsBind()
        }
      })
    } else {
      this.globalData.checkIsBind().then(() => {
        bindPartner({
          data: {
            openid: this.globalData.openid,
            scene: fromOpenid
          },
          success: res => {

          }
        })
      })
    }
  },
  _update() {
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })

    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })

    })

    updateManager.onUpdateFailed(function() {
      // 新的版本下载失败
      wx.showToast({
        title: '请检查你的网络后重试！',
        icon: 'none'
      })
    })
  },
  globalData: {
    userInfo: null,
    openid: '',
    appHot: 1,
    vipInfo: {}
  }
})